package com.anysoft.user;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anysoft.MentorConst;
import com.anysoft.utils.MentorLogger;
import com.blankj.utilcode.util.ToastUtils;
import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.StaticField;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.GetBankCardListBean;
import com.anysoft.bean.LoginOutBean;
import com.anysoft.bean.QueryReserveInfoBean;
import com.anysoft.bean.QueryRiskLevelBean;
import com.anysoft.bean.QueryUserInfoBean;
import com.anysoft.bean.UserBean;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.me.utils.PermissionManager;
import com.anysoft.user.bankcard.BankCardManagerActivity;
import com.anysoft.user.bankcard.EditMobileActivity;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.NewVersionUtils;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.StringUtils;
import com.anysoft.utils.user.icon.SelectPicPopupWindow;
import com.anysoft.utils.user.icon.UserIconFileUtil;
import com.anysoft.web.InvestChangeActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 个人设置
 * wyb 2017-03-01
 */
public class UserSettingActivity extends BaseActivity implements PermissionManager.OnPermissionListener {

    private static final String INVEST_CHANGE = "investChange";
    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    TextView rightButton;
    @BindView(R.id.circle_user_head)
    CircleImageView circle_user_head;// 头像图片

    @BindView(R.id.tv_setting_user_name)
    TextView tv_setting_user_name;//用户姓名
    @BindView(R.id.tv_setting_up_login_time_val)
    TextView tv_setting_up_login_time_val;//上次登录时间

    @BindView(R.id.tv_no_risk)
    TextView tv_no_risk;//用户未进行风险评测气泡

    @BindView(R.id.rl_set_pwd_manager)
    RelativeLayout rl_set_pwd_manager;//密码管理
    @BindView(R.id.rl_set_bank_card_manager)
    RelativeLayout rl_set_bank_card_manager;//
    @BindView(R.id.tv_bank_card_count)
    TextView tv_bank_card_count;//银行卡张数

    @BindView(R.id.rl_set_user_info)
    RelativeLayout rl_set_user_info;//个人资料
    @BindView(R.id.rl_set_risk_grade)
    RelativeLayout rl_set_risk_grade;//风险等级
    @BindView(R.id.tv_set_risk_level)
    TextView tv_set_risk_level;//风险等级
//    tv_set_risk_grade

    @BindView(R.id.rl_set_edit_phone)
    RelativeLayout rl_set_edit_phone;//修改手机号
    @BindView(R.id.rl_set_my_qr_code)
    RelativeLayout rl_set_my_qr_code;//我的二维码


    @BindView(R.id.include_notice)
    View include_notice;//
    @BindView(R.id.include_online_service)
    View include_online_service;//
    @BindView(R.id.include_service_phone)
    View include_service_phone;//
    @BindView(R.id.include_clear_space)
    View include_clear_space;//

    @BindView(R.id.include_invite_friend)
    View include_invite_friend;//
    @BindView(R.id.include_feedback)
    View include_feedback;//
    @BindView(R.id.include_about_us)
    View include_about_us;//
    @BindView(R.id.include_version_update)
    View include_version_update;//版本更新
    @BindView(R.id.ll_user_quite)
    LinearLayout ll_user_quite;//安全退出

    @BindView(R.id.tv_user_invest_change)
    TextView tv_user_invest_change;//点击转化
    @BindView(R.id.tv_user_invest_type)
    TextView tv_user_invest_type;//点击转化
    @BindView(R.id.iv_user_invest_flag) //投资转换标记
            ImageView iv_user_invest_flag;


    /**
     * 24小时客服电话
     */
    TextView tvServicePhone;
    /**
     * 空间垃圾大小
     */
    TextView tvSpaceGarbage;
    /**
     * 最新版本号
     */
    TextView tvNewVersionNo;

    private SelectPicPopupWindow menuWindow; // 自定义的头像编辑弹出框
    private static final int REQUESTCODE_PICK = 0;        // 相册选图标记
    private static final int REQUESTCODE_TAKE = 1;        // 相机拍照标记
    private static final int REQUESTCODE_CUTTING = 2;    // 图片裁切标记

    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/com.anysoft");
    private File mCurrentPhotoFile;// 照相机拍照得到的图片
    private File mCacheFile;
    private static String fileName;

    private UserBean userBean;

    /**
     * 记录用户风险等级
     */
    private String userRiskLevle = "";
    private String investorType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_user_setting);
        ButterKnife.bind(this);
        title.setText("个人设置");
        rightButton.setText("账户切换");
        rightButton.setVisibility(View.VISIBLE);
        generateNoticInfo();
        showNewVersionNo();
        tvServicePhone.setText("400-811-9999");
        tvSpaceGarbage.setText("4.6M");
    }

    /**
     * 查询用户信息
     */
    private void queryUserInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        OkGo.<String>post(HostConstant.QUERY_USER_INFO)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_userinfo(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    QueryUserInfoBean userInfoBean;

    private void parseJson_userinfo(String json) {

        try {
            userInfoBean = new Gson().fromJson(json, QueryUserInfoBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            showConfirmAlert(this, "提示", "数据解析错误");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(this, userInfoBean, json)) {
            return;
        }

        QueryUserInfoBean.DataBean data = userInfoBean.getData();
        //0：普通 1：专业
        investorType = data.getInvestorType();
        if ("1".equals(investorType)) {
            iv_user_invest_flag.setBackgroundResource(R.mipmap.invest_flag_b);
            tv_user_invest_type.setText("专业投资者");
            tv_user_invest_change.setText("转为普通投资者");
        } else {
            iv_user_invest_flag.setBackgroundResource(R.mipmap.invest_flag_a);
            tv_user_invest_type.setText("普通投资者");
            tv_user_invest_change.setText("成为专业投资者");
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        userBean = mentorApplication.userBean;
        queryReserveInfo();
        tv_setting_user_name.setText(userBean.getUserName());
        UserBean bean = findUser(findUserId());
        String pathUrl = "";
        if (bean != null) {
            pathUrl = bean.getUserImgPath();
        }
        if (!TextUtils.isEmpty(pathUrl)) {
            Logger.t("pathUrl").d(pathUrl);
            Bitmap bitmap = getDiskBitmap(pathUrl);
            if (bitmap != null) {
                circle_user_head.setImageBitmap(bitmap);
            }
        } else {
            if ("0".equals(bean.getSex())) {//女
                circle_user_head.setImageResource(R.mipmap.icon_user_w);
            } else if ("1".equals(bean.getSex())) {//男
                circle_user_head.setImageResource(R.mipmap.icon_user_m);
            } else {
                circle_user_head.setImageResource(R.mipmap.icon_user);
            }
//            circle_user_head.setImageResource(R.mipmap.icon_user);
//            circle_user_head.setBackground(getResources().getDrawable(R.mipmap.icon_user));
        }
    }

    private Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
                //System.out.println("bitmap存在");
            }
        } catch (Exception e) {
            //System.out.println("bitmap不存在");
        }
        return bitmap;
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.circle_user_head, R.id.include_notice,
            R.id.include_online_service, R.id.include_service_phone, R.id.include_clear_space,
            R.id.include_invite_friend, R.id.include_feedback, R.id.include_about_us,
            R.id.rl_set_pwd_manager, R.id.rl_set_bank_card_manager, R.id.rl_set_user_info, R.id.rl_set_risk_grade,
            R.id.include_version_update, R.id.rl_set_edit_phone, R.id.rl_set_my_qr_code, R.id.ll_user_quite,
            R.id.tv_user_invest_change})
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            switch (view.getId()) {
                case R.id.tv_user_invest_change: //点击转化
                    openActivity(INVEST_CHANGE);
                    break;
                case R.id.leftButton:
                    finish();
                    break;
                case R.id.rightButton:
                    startActivity(new Intent().setClass(mActivity, UserManageListviewActivity.class));
//                startActivity(new Intent().setClass(mActivity, UserManageActivity.class));
//                finish();
                    break;
                case R.id.circle_user_head:
                    menuWindow = new SelectPicPopupWindow(mActivity, itemsOnClick);
                    menuWindow.showAtLocation(findViewById(R.id.mainLayout),
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    break;
                case R.id.rl_set_pwd_manager:
                    openActivity(PASSWORD_MANAGER);
                    break;
                case R.id.rl_set_bank_card_manager:
                    openActivity(BANK_CARD_MANAGER);
                    break;
                case R.id.rl_set_user_info:
                    openActivity(USER_INFO_EDIT);
                    break;
                case R.id.rl_set_risk_grade:
                    startRiskActivity(userRiskLevle);
                    break;
                case R.id.include_notice:
                    showToast("include_notice");
                    break;
                case R.id.include_online_service:
                    onlineCustomer();
                    break;
                case R.id.include_service_phone:
                    callCustomerServiceTelephoneNumbers();
                    break;
                case R.id.include_clear_space:
                    showToast("include_clear_space");

                    break;
                case R.id.include_invite_friend:
                    showToast("include_invite_friend");

                    break;
                case R.id.include_feedback:
                    Intent intentFeed = new Intent(this, FeedBackActivity.class);
                    startActivity(intentFeed);

                    break;
                case R.id.include_about_us:
                    Intent intentAbout = new Intent(this, AboutUsActivity.class);
                    startActivity(intentAbout);
                    break;
                case R.id.include_version_update:
                    checkVersion();
                    break;
                case R.id.rl_set_edit_phone:
                    Intent intenEditPhone = new Intent(this, EditMobileActivity.class);
                    startActivity(intenEditPhone);
                    break;
                case R.id.rl_set_my_qr_code:
                    Intent intenQRCode = new Intent(this, QRCodeActivity.class);
                    startActivity(intenQRCode);
                    break;
                case R.id.ll_user_quite:
                    loginOut();
                    break;

            }
        }
    }

    /**
     * 调用拨号界面
     */
    private void call() {
        String phone = tvServicePhone.getText().toString();
        if ("".equals(phone.trim())) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private int openType = -1;

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                // 拍照
                case R.id.takePhotoBtn:
                    openType = 1;
                    showCameraAction();
                    break;
                // 相册选择图片
                case R.id.pickPhotoBtn:
                    openType = 2;
                    showGalleryAction();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * Open 相册
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void showGalleryAction() {
        if (PermissionManager.getInstance().checkPermissions(this, PermissionManager.PERMISSION_READ_WEITE_CAMERA)) {
            gotoGallery();
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WEITE_CAMERA,
                    PermissionManager.PERMISSION_READ_WEITE_CAMERA, this);
        }
    }

    private void gotoGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUESTCODE_PICK);
    }

    /**
     * Open camera
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void showCameraAction() {
        if (PermissionManager.getInstance().checkPermissions(this, PermissionManager.PERMISSION_READ_WEITE_CAMERA)) {
            gotoCamera();
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WEITE_CAMERA,
                    PermissionManager.PERMISSION_READ_WEITE_CAMERA, this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionSuccess() {
        if (openType == 1) {
            gotoCamera();
        } else if (openType == 2) {
            gotoGallery();
        }
    }

    @Override
    public void onPermissionFail() {
        ToastUtils.showShort("获取权限失败,请点击重试");
    }

    private void gotoCamera() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            if (!PHOTO_DIR.exists()) {
                PHOTO_DIR.mkdirs();// 创建照片的存储目录
            }
            fileName = getLoginUserIdByMD5() + ".jpg";
            mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
            Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 指定调用相机拍照后照片的储存路径
            Uri uri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(mActivity, "com.anysoft.fileprovider", mCurrentPhotoFile);
                intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                uri = Uri.fromFile(mCurrentPhotoFile);
            }
            intentC.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intentC, REQUESTCODE_TAKE);
        } else {
            Toast.makeText(mActivity, "没有SD卡", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUESTCODE_PICK:// 直接从相册获取
                    try {
                        startPhotoZoom(data.getData());
                    } catch (NullPointerException e) {
                        e.printStackTrace();// 用户点击取消操作
                    }
                    break;
                case REQUESTCODE_TAKE:// 调用相机拍照
                    if (mCurrentPhotoFile == null || !mCurrentPhotoFile.exists()) {
                        mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
                    }
                    startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
                    break;
                case REQUESTCODE_CUTTING:// 取得裁剪后的图片
                    String url = mCacheFile.getAbsolutePath();
                    userBean.setUserImgPath(url);
                    saveUser(userBean, null);
                    addPictoList(url);
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mentorApplication.needLogin()) {
            finish();
            return;
        } else {
            initData();
            queryUserInfo();
            getBindBankCardList();
            queryRiskLevel();
        }
    }

    private void addPictoList(String url) {
        Logger.t(TAG).d(url);
        //需要上传的新添加的图片
        circle_user_head.setImageURI(Uri.parse(url));
    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        String fileName = getLoginUserIdByMD5() + ".jpg";
        if (!PHOTO_DIR.exists()) {
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
        }
        mCacheFile = new File(PHOTO_DIR, fileName);
        Uri outputUri = Uri.fromFile(new File(mCacheFile.getPath()));
        String url = UserIconFileUtil.getPath(mActivity, uri);

        Logger.t("url---").d(url);
        Intent intent = new Intent("com.android.camera.action.CROP");
        //sdk>=24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            Uri imageUri = FileProvider.getUriForFile(mActivity, "com.anysoft.fileprovider", new File(url));//通过FileProvider创建一个content类型的Uri
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra("noFaceDetection", true);//去除默认的人脸识别，否则和剪裁匡重叠
            intent.setDataAndType(imageUri, "image/*");

            //19=<sdk<24
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");

            //sdk<19
        } else {
            intent.setDataAndType(uri, "image/*");
        }
        intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("output", outputUri);
        //如果图片过大，会导致oom，这里设置为false
        intent.putExtra("return-data", false);
        intent.putExtra("scale", true);
        //压缩图片
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    private void generateNoticInfo() {
        ((TextView) include_notice.findViewById(R.id.tv_user_set_title)).setText("消息通知");
        ((TextView) include_online_service.findViewById(R.id.tv_user_set_title)).setText("在线客服");
        ((TextView) include_service_phone.findViewById(R.id.tv_user_set_title)).setText("24小时客服电话");
        ((TextView) include_clear_space.findViewById(R.id.tv_user_set_title)).setText("清理空间");
        tvServicePhone = (TextView) include_service_phone.findViewById(R.id.tv_user_set_val);
        tvSpaceGarbage = (TextView) include_clear_space.findViewById(R.id.tv_user_set_val);
        tvServicePhone.setVisibility(View.VISIBLE);
        tvSpaceGarbage.setVisibility(View.VISIBLE);

        ((TextView) include_invite_friend.findViewById(R.id.tv_user_set_title)).setText("邀请好友");
        ((TextView) include_feedback.findViewById(R.id.tv_user_set_title)).setText("意见反馈");
        ((TextView) include_about_us.findViewById(R.id.tv_user_set_title)).setText("关于我们");
        ((TextView) include_version_update.findViewById(R.id.tv_user_set_title)).setText("版本更新");
        tvNewVersionNo = (TextView) include_version_update.findViewById(R.id.tv_user_set_val);
        tvNewVersionNo.setVisibility(View.VISIBLE);
    }

    /**
     * 密码管理
     */
    private final static String PASSWORD_MANAGER = "passwordmanager";
    /**
     * 银行卡管理
     */
    private final static String BANK_CARD_MANAGER = "bankcardmanager";
    /**
     * 个人资料修改
     */
    private final static String USER_INFO_EDIT = "userinfoedit";

    private void openActivity(String type) {
        Intent intent = null;
        if (PASSWORD_MANAGER.equals(type)) {
            intent = new Intent(this, PasswordManageActivity.class);
            startActivity(intent);
        } else if (BANK_CARD_MANAGER.equals(type)) {
            intent = new Intent(this, BankCardManagerActivity.class);
            startActivity(intent);
        } else if (USER_INFO_EDIT.equals(type)) {
            intent = new Intent(this, UserInfoEditActivity.class);
            startActivity(intent);
        } else if (INVEST_CHANGE.equals(type)) { //跳转到转化页面
            intent = new Intent(this, InvestChangeActivity.class);
            intent.putExtra("investorType", investorType);
            startActivity(intent);
        }
    }

    /**
     * 28.	预留信息和上次登录时间查询
     */
    private void queryReserveInfo() {

        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        OkGo.<String>post(HostConstant.QUERY_RESERVE_INFO)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "获取预留信息和上次登录时间查询", response.body());
                        parseJson_reserve(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 获取用户名下绑定的所有银行卡信息
     */
    private void getBindBankCardList() {
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());//
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());//

        OkGo.<String>post(HostConstant.QUERY_CUSTOMER_BANK)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_bank(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(MentorConst.INTERNET_ERROR);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 23.	用户风险等级查询
     */
    private void queryRiskLevel() {

        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        OkGo.<String>post(HostConstant.QUERY_RISK_LEVEL)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_level(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析服务端返回的数据-用户预留信息和上次登录时间
     *
     * @param json
     */
    private void parseJson_reserve(String json) {
        QueryReserveInfoBean bean;
        try {
            bean = new Gson().fromJson(json, QueryReserveInfoBean.class);
        } catch (Exception exception) {
//            showToast("数据解析异常，请联系管理员");
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, json)) {
            return;
        }
//        ResultBean resultBean = checkStateBean(bean, json);
//        if (!resultBean.isSuccess()) {
//            showToast(resultBean.getTip());
//            return;
//        }

        if (bean == null || bean.getData() == null) {
            return;
        }
        tv_setting_up_login_time_val.setText(bean.getData().getLoginLastTime() + "");
        if (!StringUtils.isNullOrEmpty(bean.getData().getLoginLastTime()) && bean.getData().getLoginLastTime().length() > 16) {
            tv_setting_up_login_time_val.setText(bean.getData().getLoginLastTime().substring(0, 16) + "");
        }
    }

    /**
     * 解析服务端返回的数据-已开通银行卡
     *
     * @param json
     */
    private void parseJson_bank(String json) {
        GetBankCardListBean bean;
        try {
            bean = new Gson().fromJson(json, GetBankCardListBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, json)) {
            return;
        }
//        ResultBean resultBean = checkStateBean(bean, json);
//        if (!resultBean.isSuccess()) {
//            showToast(resultBean.getTip());
//            return;
//        }

        if (bean == null || bean.getData() == null) {
            return;
        }
        tv_bank_card_count.setText(bean.getData().size() + "张");
    }

    /**
     * 解析返回的 用户风险等级json
     *
     * @param response
     */
    private void parseJson_level(String response) {
        QueryRiskLevelBean bean;

        try {
            bean = new Gson().fromJson(response, QueryRiskLevelBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            showConfirmAlert(this, "提示", "数据解析错误");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }
        userRiskLevle = bean.getData().getLevel();
        if (StringUtils.isNullOrEmpty(userRiskLevle)) {
            tv_set_risk_level.setText("");
            tv_no_risk.setVisibility(View.VISIBLE);
            return;
        }
        tv_no_risk.setVisibility(View.GONE);
        tv_set_risk_level.setText(bean.getData().getLevelName());
    }

    public void loginOut() {
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());

        OkGo.<String>post(HostConstant.LOGIN_OUT)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateLoginOut(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateLoginOut(String json) {

        LoginOutBean bean;

        try {
            bean = new Gson().fromJson(json, LoginOutBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            showConfirmAlert(this, "提示", "数据解析错误");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }
        mentorApplication.signOut();
        AnalyticsEventUtils.toLogoutEvent(this);
        finish();
    }

    public void checkVersion() {
        Map<String, String> params = new HashMap<>();
        params.put("plantform", "2");
        OkGo.<String>post(HostConstant.UPDATE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "版本检测:", response.body());
                        if (TextUtils.isEmpty(response.body())) {
                            showConfirmAlert(mActivity, "数据返回为空");
                        }
                        NewVersionUtils.checkVersion(mActivity, response.body());
                        showNewVersionNo();
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 展示版本号
     */
    private void showNewVersionNo() {
        String sNewVersionNo = PreferencesUtils.getString(this, MentorConst.NEW_VERSION_NO, "");
        String sNewVersion = StringUtils.removePointString(sNewVersionNo);
        String sLocalVersionNo = StaticField.getVersionName(this);
        String sLocalVersion = StringUtils.removePointString(sLocalVersionNo);
        if (!StringUtils.isNullOrEmpty(sNewVersion) && sNewVersion.compareTo(sLocalVersion) > 0) {
            tvNewVersionNo.setText("V" + sNewVersionNo + "");
        } else {
            tvNewVersionNo.setText("V" + sLocalVersionNo + "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

}
